package com.android.settings.audio.peq.qr.encoder;


import static com.android.settings.audio.peq.qr.Constant.QR_SCHEMA_V1_PEQ;

import android.text.TextUtils;

import com.android.settings.audio.peq.qr.QrManager;
import com.android.settings.audio.peq.qr.annotation.QrImpl;
import com.android.settings.audio.peq.soundeffect.PluginDataManager;
import com.android.settings.audio.peq.util.Base64;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.LogPlus;

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;

/**
 * Created by We on 2023/5/25
 */
@QrImpl(id = QR_SCHEMA_V1_PEQ)
public class PeqV1Encoder extends QrManager.AbsEncoder {
    public PeqV1Encoder() {
        this.id = QR_SCHEMA_V1_PEQ; //by inject
    }

    @Override
    public String generateContent(byte[] data) {
        final StringBuilder sb = new StringBuilder(this.id);
        String peqDataBase64Str = Base64.encode(data);
        return sb.append(peqDataBase64Str).toString();
    }

    @Override
    public byte[] toBytes(Object dataEntity) throws Exception {
        PluginDataManager.PeqData peqData = null;
        if(dataEntity instanceof PluginDataManager.PeqData){
            peqData = (PluginDataManager.PeqData) dataEntity;
        }
        if (peqData == null) {
            throw new RuntimeException("peqData is null");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] nameBytes = peqData.name.getBytes();
        baos.write(nameBytes.length);
        baos.write(nameBytes);//name

        if (BuildConfig.DEBUG) LogPlus.d("###device:" + peqData.device);
        byte[] deviceBytes = TextUtils.isEmpty(peqData.device) ? new byte[0] : peqData.device.getBytes();
        baos.write(deviceBytes.length);
        baos.write(deviceBytes);//device

        if (BuildConfig.DEBUG) LogPlus.d("###description:" + peqData.description);
        byte[] descriptionBytes = TextUtils.isEmpty(peqData.description) ? new byte[0] : peqData.description.getBytes();
        baos.write(descriptionBytes.length);
        baos.write(descriptionBytes);//description

        baos.write(ByteBuffer.allocate(4).putFloat((float) peqData.pre_amp).array());//preamp
        for (PluginDataManager.BandItem band : peqData.bands) {
            baos.write(band.filter);//filter
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.freq).array());//freq
            baos.write(band.on);//on
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.gain).array());//gain
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.q).array());//q
        }
        baos.close();
        return baos.toByteArray();
    }
}
